import React, { PureComponent, Fragment } from 'react';
import { connect } from 'react-redux';

import { Layout } from 'antd';
import {
    PageHeader,
    Table,
    ButtonEvent,
    SearchForm,
    Form,
    Drawer,
    Tip,
    Status
} from '../../../../components';
import { managerService } from '../../../../service';
import { managerAction as actionCreates, mainAction } from '../../../../store/action';
import { Luck } from '../../../../utils';

const breadcrumbList = [{
    title: '权限管理',
    href: '/auth',
},{
    title: '管理员管理',
    href: '/auth/manager',
}];

const searchdata = [
    {type:'input',title:'用户名',name:'like__username',value:'',placeholder:"请输入管理员名称"}
];

class Manager extends PureComponent{
    state = {
        visible : false,
        title : '管理员管理',
        drawertitle : '添加管理员',
        //表格colums
        columns:[
            {title: '用户名',dataIndex: 'username',width:200,sorter:true}
            ,{title: '昵称',dataIndex: 'nickname',width:200}
            ,{title: '上次登陆时间',dataIndex: 'last_login_time',width:150,render:(value)=>Luck.tamptotime(value)}
            ,{title: '上次登陆IP',dataIndex: 'last_login_ip',width:150,render:(value)=>Luck.strtoip(value)}
            ,{title: '备注',dataIndex: 'remark',width:450,onCell: () =>{ return {style: {whiteSpace: 'nowrap',maxWidth: 300}} }}
            ,{title: '状态',dataIndex: 'status',width:100,render:(value,row)=>{
                return <Status ontext="启用" offtext="禁用" value={value} onClick = { (bool)=>{ this.status(bool,row) } } />
            }}
            ,{ title: '操作', key: 'operation',fixed:'right', width: 200, render: (value) =><ButtonEvent data={ [
                {key:1,value:'分配角色',type:"primary",size:'small',onClick:()=>{
                    this.initSet(value)
                }},
                {key:2,value:'修改',size:'small',onClick:()=>{
                    this.initEdit(value)
                }},
                {key:3,type:'danger',value:'删除',size:'small',onClick:()=>{
                    this.initDel(value)
                }}
            ]}/> }
        ],
        //选中数据
        selectedRowKeys:[],
        selectedRows:[],
        selectedIds:[],
        //表格控制按钮
        tableBtn:[
            {key:1,type:'primary',value:'添加',onClick:()=>{ this.openDrawer('add'); }},
            {key:2,value:'修改',onClick:()=>{ this.openDrawer('edit'); }},
            {key:3,type:'danger',value:'删除',onClick:()=>{ this.openDrawer('del'); }}
        ],
        //弹出表单按钮
        footBar : [],
        fieldBar:{
            cancel:{key:1,value:'取消',onClick:()=>{ this.closeDrawer(); }}
        },
        //销毁抽屉
        destroyOnClose:true,
        //form表单项目
        inputdata : [],
        //翻页
        pagination : {
            current:1,
            onShowSizeChange:(cur,pageSize)=>{this.changeRowsPage(cur,pageSize)},
            //onChange:(cur,pageSize)=>{this.changePage(cur,pageSize)}
        }
    }

    render(){
        const { loading, list, emptyText, total, pageSize, page } = this.props;
        const { visible, title, drawertitle, tableBtn, selectedRowKeys, footBar, destroyOnClose, inputdata, columns, pagination } = this.state;
        pagination.total = total;
        pagination.current = page;
        pagination.pageSize=pageSize;

        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        }
        const locale = {
            emptyText
        }
        const action = <ButtonEvent data={ [
            {key:1,type:'primary',value:'刷新',size:'small',onClick:()=>{
                this.reset()
            }}
        ]}/>;
        return(
            <Fragment>
                <PageHeader title={title} breadcrumbList={ breadcrumbList } action = {action} />
                
                <Layout.Content style={{margin:'24px',padding:'24px 32px 8px',backgroundColor:'#fff'}}>
                    <SearchForm
                        style={{ marginBottom: 16 }}
                        layout = 'inline'
                        data={searchdata}
                        reset={this.reset}
                        submit={this.search}
                        wrappedComponentRef={(form) => this.searchRef = form}
                    />
                    <ButtonEvent
                        data={ tableBtn }
                        style={{marginBottom:16}}
                    />
                    <Table
                        columns={columns}
                        rowSelection={ rowSelection }
                        dataSource={ list }
                        loading = { loading }
                        pagination ={ pagination }
                        locale = { locale }
                        onChange = { this.handleChange }
                    />
                </Layout.Content>

                {/* 弹框 onClose 必须存在 */}
                <Drawer title={drawertitle} visible={visible} footBar={footBar} destroyOnClose={destroyOnClose} onClose={this.closeDrawer} width="450px">
                    <Form
                        layout = 'horizontal'
                        data = {inputdata}
                        wrappedComponentRef={(form) => this.formRef = form}
                    />
                </Drawer>
            </Fragment>
        );
    }

    /**
     * 查询开始
     */
    //查询数据
    search = (name)=>{
        const { bindList, bindLoading, bindCurrent, pageSize } = this.props;
        bindLoading(true)
        bindList({page:1,rows:pageSize,...name})
        bindCurrent(1);
    }
    //重置查询
    reset = () => {
        const { bindList, bindLoading, pageSize, page } = this.props;
        bindLoading(true)
        bindList({page,rows:pageSize})
        
    }
    //排序和翻页
    handleChange = (pagination, filters, sorter)=>{
        const { bindList, bindLoading } = this.props;
        let values = this.searchRef.getItemsValue();
        let order={};
        if(Object.keys(sorter).length>0){
            order={
                field:sorter.field,
                order:sorter.order==="descend" ? 'desc':'asc'
            }
        }
        bindLoading(true)
        bindList({page:pagination.current,rows:pagination.pageSize,...order,...values})
    }
    /** 查询结束 */

    //翻页
    /*changePage = (cur,pagesize)=>{
        const { bindList, bindLoading } = this.props;
        bindLoading(true);
        bindList({page:cur,rows:pagesize})
    }*/
    //每页条数
    changeRowsPage = (cur,pagesize)=>{
        const { bindPageSize } = this.props;
        //bindLoading(true);
        bindPageSize(pagesize);
        //bindLoading,bindList({page:cur,rows:pagesize})
    }
    //选择
    onSelectChange=(selectedRowKeys, selectedRows) => {
        let newselectedRows=[];
        let selectedIds=[];
        for (let i = 0; i < selectedRows.length; i++) {
            newselectedRows.push(selectedRows[i]);
            selectedIds.push(selectedRows[i].id);
        }
        this.setState({ 
            selectedRowKeys,
            selectedRows:newselectedRows,
            selectedIds
        });
    }

    //抽屉开始-----
    //关闭抽屉
    closeDrawer=()=>{
        this.setState({
            visible:false
        })
    }
    /**
     * 打开抽屉
     */
    openDrawer=(type)=>{
        const { selectedRows, selectedIds } = this.state;
        switch (type) {
            case 'add':
                this.addForm();
                this.setState({
                    visible:true,
                    drawertitle:'添加管理员'
                });
                break;
            case 'edit':
                if(selectedRows.length === 1){
                    this.editForm(selectedRows[0]);
                    this.setState({
                        visible:true,
                        drawertitle:'修改管理员'
                    });
                }else{
                    Tip.Message('必须选择一条且只能选择一条数据进行修改','error')
                }
                break;
            case 'del':
                if(selectedIds.length > 0){
                    this.delete(selectedIds);
                }else{
                    Tip.Message('至少选择一条数据进行删除','error')
                }
                break;
            default:
                break;
        }
    }
    initSet = async (obj)=>{
        const { allrole } = this.props;
        let footBar = [{key:1,value:'取消',onClick:()=>{
            this.closeDrawer();
        }},{key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{ this.saveRole(); }}];

        let options=[];
        for(let i=0;i<allrole.length;i++){
            let o = {
                value:allrole[i].id,
                name:allrole[i].title
            }
            options.push(o);
        }
        let gids = await managerService.getgroup_id({'id':obj['id']});
        let field = [
            {type:'input.hidden',title:'ID',name:'uid',value:obj['id'],disabled:true},
            {type:'checkbox',title:'角色',name:'group_id',value:gids,options},
        ];
        
        this.setState({
            visible:true,
            drawertitle:"给 <"+ obj.username +"> 分配角色",
            footBar:footBar,
            inputdata:field
        });
    }
    saveRole = async ()=>{
        let values = await this.formRef.getItemsValue();
        this.changeBtnLoading(true);
        if(values){
            try{
                let res = await managerService.post('setaccess',values);
                this.tipMsg(res);
            }catch{
                this.tipMsg({code:3,msg:"网络错误"});
            }
        }
        setTimeout(()=>{
            this.changeBtnLoading(false);
        },500);
    }
    initDel = (obj)=>{
        let id=[];
        id.push(obj.id)
        this.delete(id);
    }
    delete = (arr)=>{
        Tip.Modal('您真的要删除?','confirm',{
            onOk:async ()=>{
                let res = await managerService.post('del',arr);
                this.tipMsg(res,'del');
            }
        })
    }
    initEdit = (obj)=>{
        this.setState({
            visible:true,
            drawertitle:'修改管理员'
        });
        this.editForm(obj);
    }
    //编辑数据
    editForm = (obj)=>{
        let { fielddata } = this.props;
        let fielddataarr=[],fieldBararr=[];
        for (let i in fielddata) {
            let o = {};
            o = Object.assign({},fielddata[i]);
            o.value = obj[i];
            fielddataarr.push(o)
        }
        let cancel = {key:1,value:'取消',onClick:()=>{
            this.closeDrawer();
        }};
        fieldBararr.push(cancel);
        let edit={key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{ this.saveEdit('edit'); }};
        fieldBararr.push(edit);

        let id = {type:'input.hidden',title:'ID',name:'id',value:obj['id'],disabled:true};
        fielddataarr.push(id)
        this.setState({
            inputdata:fielddataarr,
            footBar:fieldBararr
        })

    }
    addForm = ()=>{
        let { fielddata } = this.props;
        let { fieldBar } = this.state;
        let fielddataarr=[],fieldBararr=[];
        for (let i in fielddata) {
            let o = {};
            o = Object.assign({},fielddata[i]);
            fielddataarr.push(o)
        }
        fieldBararr.push(fieldBar.cancel);
        let add={key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{ this.saveEdit('add'); }};
        fieldBararr.push(add);
        this.setState({
            inputdata:fielddataarr,
            footBar:fieldBararr
        })
    }
    //添加数据
    saveEdit = async (type)=>{
        this.changeBtnLoading(true);
        let values = await this.formRef.getItemsValue();
        if(values){
            let res = await managerService.post(type,values);
            this.tipMsg(res);
        }
        setTimeout(()=>{
            this.changeBtnLoading(false);
        },500);
    }
    changeBtnLoading = (bool)=>{
        this.props.bindBtnLoading(bool)
    }
    //抽屉结束

    //状态修改
    status = async (value,item)=>{
        let data={
            id:item.id,
            username:item.username
        };
        if(value){
            data['status']=1;
        }else{
            data['status']=0;
        }
        let res = await managerService.post('edit',data);
        this.tipMsg(res);
    }

    //消息提示
    tipMsg = (res,type='')=>{
        const { bindList, bindLoading, bindCurrent, pageSize, page } = this.props;
        if(res.code===0){
            this.closeDrawer();
            Tip.Message(res.msg,'success');
            bindLoading(true)
            if(type==='del'){
                bindList({page:1,rows:pageSize})
                bindCurrent(1);
            }else{
                bindList({page,rows:pageSize})
            }
        }else{
            Tip.Message(res.msg,'error')
        }
    }

    async componentDidMount(){
        const { bindList, pageSize, fielddata, page, btnloading, bindSetRole } = this.props;
        let { pagination } = this.state;

        let { fieldBar } = this.state;
        let fielddataarr=[],fieldBararr=[];
        for (let i in fielddata) {
            let o = {};
            o = Object.assign({},fielddata[i]);
            fielddataarr.push(o)
        }
        
        fieldBararr.push(fieldBar.cancel);
        let add={key:2,type:'primary',value:'保存',loading:btnloading,onClick:()=>{ this.saveEdit('add'); }};
        fieldBararr.push(add);
        
        this.setState({
            inputdata:fielddataarr,
            footBar:fieldBararr,
            pagination
        });

        //获取配置权限列表
        let role = await managerService.getrole();
        bindSetRole(role)

        bindList({page,rows:pageSize})
    }
}

const mapStateToProps = (state)=>{
    const name = 'manager';
    const list = state.getIn([name,'list']).toJS();
    const allrole = state.getIn([name,'allrole']).toJS();
    const loading = state.getIn([name,'loading']);
    const total = state.getIn([name,'total']);
    const page = state.getIn([name,'page']);
    const pageSize = state.getIn([name,'pageSize']);
    const emptyText = state.getIn([name,'emptyText']);
    const fielddata = state.getIn([name,'fielddata']).toJS(); 
    
    const btnloading = state.getIn(['main','btnloading']);
    return{
        list,
        loading,
        total,
        page,
        pageSize,
        emptyText,
        btnloading,
        fielddata,
        allrole
    }
}
const mapDispatchToProps = (dispatch)=>{
    return{
        bindLoading(loading){
            dispatch(actionCreates.setLoading(loading))
        },
        bindPageSize(pageSize){
            dispatch(actionCreates.setPagesize(pageSize));
        },
        bindCurrent(cur){
            dispatch(actionCreates.setPage(cur));
        },
        bindBtnLoading(bool){
            dispatch(mainAction.setBtnLoading(bool));
        },
        bindSetRole(role){
            dispatch(actionCreates.setAllRole(role));
        },
        async bindList(data={}){
            let res = await managerService.getlist(data);
            if(res.code === 0){
                let list=res.data;
                dispatch(actionCreates.getList(list.rows,list.total));
                dispatch(actionCreates.setPage(data.page))
            }else{
                dispatch(actionCreates.setEmptyText(res.msg));
            }
            dispatch(actionCreates.setLoading(false));
        }
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(Manager);